/*
 * Plot.java
 *
 * Created on 15 ����� 2007, 3:22 ��
 */
package p2p.simulator.gui;

import java.awt.*;
import javax.imageio.*;
import java.io.*;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.swing.ImageIcon;
import org.jCharts.Chart;
import org.jCharts.chartData.AxisChartDataSet;
import org.jCharts.chartData.ChartDataException;
import org.jCharts.chartData.DataSeries;
import org.jCharts.encoders.PNGEncoder;
import org.jCharts.properties.*;
import org.jCharts.axisChart.*;
import org.jCharts.properties.util.ChartStroke;
import org.jCharts.types.ChartType;

/**
 *
 * @author  george
 */
public class Plot extends javax.swing.JFrame implements Runnable {

    private String title;

    /** Creates new form Plot */
    public Plot(HashMap ft, String title, String metric) {

        this.title = title;
        super.setTitle(title);
        initComponents();

        constructPlot(ft, metric);
        paintPlot("plot.png");
    //setVisible(true);
    }

    public void run() {
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBounds(new java.awt.Rectangle(0, 0, 0, 0));

        jPanel1.setPreferredSize(new java.awt.Dimension(600, 700));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIconTextGap(0);
        jLabel1.setPreferredSize(new java.awt.Dimension(600, 700));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 700, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jMenu1.setText("File");

        jMenuItem1.setText("Save");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setText("Quit");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 700, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // Save from menu

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                String filename = (new SaveDialogWindow("png")).getFilename();
                
                try {
                    BufferedImage image = ImageIO.read(new File("plot.png"));
                    ImageIO.write(image, "png", new File(filename));

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // Quit from menu

        dispose();
    }//GEN-LAST:event_jMenuItem2ActionPerformed
    
    private void constructPlot(HashMap ft, String metric) {
        
            int i, j, size, value, key;
            double[][] data;
            double avrg = 0, sum = 0, total = 0;
            Set keySet;
            ArrayList<Integer> keyArray;
            Iterator it;
            
            size = ft.size();
            data = new double[2][size];
            
            String[] xAxisLabels= new String[size];
            String xAxisTitle = "Frequency";
            String yAxisTitle = metric;
                        
            String[] legendLabels= { "Frequency", "Average"};
            Paint[] paints= {Color.BLUE, Color.GREEN};
            
            
            keySet = ft.keySet();
            it = keySet.iterator();
            //keyArray = new ArrayList<Integer>(keySet);
            //Collections.sort(keyArray);
            //it = keyArray.iterator();
            
            j = 0;
            while (it.hasNext()) {
                key = Integer.parseInt(it.next().toString());
                value = Integer.parseInt(ft.get(""+key).toString());
                sum += key * value;
                total += value;

                data[0][j] = key;
                xAxisLabels[j] = new String(""+value);
                j++;
            }
            avrg = sum / total;
            
            for (j = 0; j < size; j++) {    
                data[1][j] = avrg;
            }
            
            DataSeries dataSeries = new DataSeries( xAxisLabels, xAxisTitle, yAxisTitle, title);
            boolean[] fillPointFlags = {true, true};            
            Shape[] shapes = {PointChartProperties.SHAPE_TRIANGLE, PointChartProperties.SHAPE_CIRCLE };
            //Stroke[] strokes= { null, null, null};
            //LineChartProperties lineChartProperties= new LineChartProperties( strokes, shapes );
            PointChartProperties pointChartProperties = new PointChartProperties(shapes, fillPointFlags, paints);
            AxisChartDataSet axisChartDataSet;
            try {
                axisChartDataSet = new AxisChartDataSet(data, legendLabels, paints, ChartType.POINT, pointChartProperties);
                dataSeries.addIAxisPlotDataSet( axisChartDataSet );
            } catch (ChartDataException ex) {
                ex.printStackTrace();
            }

            ChartProperties chartProperties= new ChartProperties();
            AxisProperties axisProperties= new AxisProperties();
            LegendProperties legendProperties= new LegendProperties();
            ChartStroke xAxisGridLines= new ChartStroke( new BasicStroke( 1.0f ), Color.GRAY );
            axisProperties.getYAxisProperties().setGridLineChartStroke( xAxisGridLines );
            axisProperties.getYAxisProperties().setShowGridLines( AxisTypeProperties.GRID_LINES_ONLY_WITH_LABELS );
            //axisProperties.getXAxisProperties().setGridLineChartStroke( xAxisGridLines );
            //axisProperties.getXAxisProperties().setShowGridLines( AxisTypeProperties.GRID_LINES_ONLY_WITH_LABELS );

            AxisChart axisChart= new AxisChart( dataSeries, chartProperties, axisProperties, legendProperties, 700, 600 );
            exportImage(axisChart, "plot");
            //System.out.println("CONSTRUCT PLOT");   
    }
    
    private void paintPlot(String operation) {
        try {
            if((new File(operation)).exists())
                jLabel1.setIcon(new ImageIcon(ImageIO.read(new File("plot.png"))));
        } catch (IOException ex) {
                ex.printStackTrace();
        }
    }
    
    private void exportImage( Chart chart, String fileName )
    {
            String extension= ".png";
            FileOutputStream fileOutputStream;

            try
            {       
                    fileOutputStream= new FileOutputStream( fileName + extension );
                    PNGEncoder.encode( chart, fileOutputStream );
                    fileOutputStream.flush();
                    fileOutputStream.close();
            }
            catch( Throwable throwable )
            {
                    throwable.printStackTrace();
            }
    }
 
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
    private String operation;
    public final static int EXPERIMENT = 1;
    public final static int LOAD_BALANCE = 2;

    private int numOfNodes;

    private String dist;
    
}
